﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.Web.Mvc.UI;
using TomNet.Web.Mvc;
using System.ComponentModel;
using TomNet.Web.Mvc.Security;
using TomNet.IMSC.Web.Areas.Decoration.Models;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Web.Filters;

namespace TomNet.IMSC.Web.Areas.Decoration.Controllers
{
    [Description("装修-装修设计方案")]
    [GlobalAuthorization]
    public class DecorationCompanyCaseController : BaseController
    {
        public IDecorationCompanyCaseContract DecorationCompanyCaseContract { get; set; }//装修方案
        public IDecorationCompanyCaseItemContract DecorationCompanyCaseItemContract { get; set; }//案例项目
        public IDictionaryContract DictionaryContract { get; set; }//字典
        // GET: Decoration/DecorationCompanyCase
        [Description("装修-装修设计方案列表")]
        public ActionResult CaseIndex()
        {
            return View();
        }
        #region 装修方案查询
        /// <summary>
        /// 装修方案查询
        /// </summary>
        /// <param name="pageIndex">索引</param>
        /// <param name="pageSize">页面大小</param>
        /// <param name="search">关键字</param>
        /// <returns></returns>
        [Description("装修-装修设计方案列表")]
        public ActionResult GetList(int pageIndex, int pageSize, int id, string search = "")
        {
            var query = from q in DecorationCompanyCaseContract.Entities
                        where q.DecorationCompanyID == id
                        select new DecorationCompanyCaseNew
                        {
                            Id = q.Id,
                            DecorationCompanyID = q.DecorationCompanyID,
                            Name = q.Name,
                            ShowPrice = q.ShowPrice,
                            HouseType = (from d in DictionaryContract.Entities
                                        where d.Id == q.HouseType
                                        select d.Value).FirstOrDefault().ToString(),
                            Area = q.Area,
                            AreaTag = (from d in DictionaryContract.Entities
                                       where d.Id == q.AreaTag
                                       select d.Value).FirstOrDefault().ToString(),
                            Style = (from d in DictionaryContract.Entities
                                     where d.Id == q.Style
                                     select d.Value).FirstOrDefault().ToString(),
                            TimeLimit = q.TimeLimit,
                            Designer = q.Designer,
                            OpusType = q.OpusType
                        };

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }
            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationCompanyCaseNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationCompanyCaseNew> gridData = new GridData<DecorationCompanyCaseNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        [Description("装修-添加设计方案")]
        public ActionResult CaseInsert()
        {
            ViewData["Style"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseStyle").ToList();
            ViewData["HouseType"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseHouseType").ToList();
            ViewData["Area"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseArea").ToList();
            return View();
        }
        /// <summary>
        /// 添加方案
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("装修-添加设计方案")]
        public ActionResult InsertAsync(DecorationCompanyCase entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyCaseContract.CheckExists(d => d.Name.Equals(entity.Name));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修方案名称";
                }
                else
                {
                    var count = DecorationCompanyCaseContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #region 装修-修改装修公司
        [Description("装修-修改设计方案")]
        public ActionResult CaseEdit(int id)
        {
            var entity = DecorationCompanyCaseContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            ViewData["Style"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseStyle").ToList();
            ViewData["HouseType"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseHouseType").ToList();
            ViewData["Area"] = DictionaryContract.Entities.Where(a => a.Name == "DecorationCaseArea").ToList();
            return View();
        }
        [Description("装修-修改设计方案")]
        [HttpPost, AjaxOnly]
        public ActionResult EditAsync(DecorationCompanyCase entity)
        {
            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyCaseContract.CheckExists(d => d.Name.Equals(entity.Name) && d.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修设计方案";
                }
                else
                {
                    var count = DecorationCompanyCaseContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-删除装修公司设计方案
        [Description("装修-删除设计方案")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                DecorationCompanyCaseContract.Delete(d => idsInt.Contains(d.Id));
                //DecorationCompanyContract.UpdateDirect(m => idsInt.Contains(m.Id));

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        [Description("装修-案例项目列表")]
        public ActionResult CaseItemIndex()
        {
            return View();
        }

        #region 案例项目列表
        [Description("装修-案例项目列表")]
        public ActionResult GetItemList(int pageIndex, int pageSize, int id, string search = "")
        {
            var query = from q in DecorationCompanyCaseItemContract.Entities where q.DecorationCompanyCaseID == id select q;

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Title.Contains(search));
            }
            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationCompanyCaseItem>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationCompanyCaseItem> gridData = new GridData<DecorationCompanyCaseItem>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion
        [Description("装修-添加设计方案项目")]
        public ActionResult CaseItemInsert()
        {
            ViewBag.HouseType = from d in DictionaryContract.Entities select d;
            return View();
        }

        /// <summary>
        /// 添加方案项目
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("装修-添加设计方案项目")]
        public ActionResult CaseItemInsertAsync(DecorationCompanyCaseItem entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyCaseItemContract.CheckExists(d => d.Title.Equals(entity.Title));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修方案项目";
                }
                else
                {
                    var count = DecorationCompanyCaseItemContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        #region 装修-删除装修公司设计方案
        [Description("装修-删除设计方案")]
        [HttpPost, AjaxOnly]
        public ActionResult CaseItemDeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                DecorationCompanyCaseItemContract.Delete(d => idsInt.Contains(d.Id));
                //DecorationCompanyContract.UpdateDirect(m => idsInt.Contains(m.Id));

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
    }
}